<?php
/**
 * @package		com_puser 
 */

defined('_JEXEC') or die;

JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/com_puser/tables');
JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/com_jobs/tables');

/**
 * Registration controller class for Users.
 */
class PCompanyModelPassword extends JModelLegacy
{
	/**
	 * set new pass for reset master employer users 
	 */
	public function setNewPass() {
      /* disable token to avoid session timeout issue 
      if(!PSession::checkToken('post')) {
         $this->setError('非法的系统安全码');
         return false;
      }
      */
      if(!isDevMode()) {
         $securimage = new Securimage();
         if($securimage->check(JRequest::getString('captcha_code', '')) == false) {
            $this->setError("输入的安全码与图片显示不符,请重新输入<captcha_code></captcha_code>");
            return false; 
         }
      } 
      $post = JRequest::get("post");
      $token = JRequest::getString('token', '');
      $email = JRequest::getString('email', '');

      if(empty($token) || empty($email)) {
         $this->setError("非法的重置链接");
         return false; 
      }

      $db = PFactory::getDbo();

      $sql = "SELECT u.id FROM #__comprofiler AS a " . 
             " LEFT JOIN #__users AS u ON u.id=a.user_id " .
             "WHERE u.block=0 AND a.passwdreset_token = " . $db->quote($token) . " AND u.email = " . $db->quote($email);

      $db->setQuery($sql);
      $user = $db->loadObject();

      $subaccount = false; 
      if (!$user) {
         if(OC_Preferences::getValue($email, 'owncloud', 'lostpassword') === hash('sha256', $token)) {
            $subaccount = true; 
         }
         else {
            $this->setError("邮箱地址无效或无效的符记");
            return false; 
         }
      }

      if(!preg_match("/^[^\s]{6,255}$/i", JRequest::getString('password', "", "post", JREQUEST_NOTRIM))) {
         $this->setError('请输入有效的密码，至少6个字符，可包含数字、字母或其他字符，不允许使用空格');
         return false;
      }

      if(empty($post['password']) || empty($post['password2']) ||
         $post['password'] != $post['password2']) {
         $this->setError("密码和验证密码不一致，请重试.");
         return false; 
      }

      if(!$subaccount) {     
         // save users information 
         $user = PFactory::getUser($user->id);
         if (!$user->bind($post)) {
            $this->setError("绑定用户数据失败: " . $user->getError());
            return false;
         }

         // Store the data.
         if (!$user->save()) {
            $this->setError("保存用户数据失败: " . $user->getError());
            return false;
         }

         /* remove reset token */
         $sql = "UPDATE #__comprofiler SET passwdreset_token = '' WHERE user_id = " . $user->id; 
         $db->setQuery($sql);
         $db->query();
         return true; 
      }
      else {
         if(OC_User::setPassword($email, $post['password'])) {
            OC_Preferences::deleteKey($email, 'owncloud', 'lostpassword');
            OC_User::unsetMagicInCookie();
            return true; 
         }
      }

      return false; 
	}

   public function getUserFromToken() {

      $token = JRequest::getString('token', '');
      $email = JRequest::getString('email', '');

      if(empty($token) || empty($email)) {
         $this->setError("非法的重置链接");
         return false; 
      }

      $db = PFactory::getDbo();

      $sql = "SELECT email, passwdreset_token FROM #__comprofiler AS a " . 
             " LEFT JOIN #__users AS u ON u.id=a.user_id " .
             "WHERE u.block=0 AND a.passwdreset_token = " . $db->quote(hash('sha256', $token)) . " AND u.email = " . $db->quote($email);

      $db->setQuery($sql);
      $user = $db->loadObject();


      if (!$user) {
         /* check if we are sub account */
         if(OC_Preferences::getValue($email, 'owncloud', 'lostpassword') === hash('sha256', $token)) {
            $user = array('email'=>$email, 'passwdreset_token'=>$token); 
            $user = JArrayHelper::toObject($user); 
         }
         else {
            $this->setError("邮箱地址无效或无效的符记");
            return false; 
         }
      }

      return $user; 
   }

   public function sendPassReset() {
      /* disable token for session timeout issue 
      if(!PSession::checkToken('post')) {
         $this->setError('非法的系统安全码');
         return false;
      }
      */
      if(!isDevMode()) {
         $securimage = new Securimage();
      
         if($securimage->check(JRequest::getString('captcha_code', '')) == false) {
            $this->setError("输入的安全码与图片显示不符,请重新输入<captcha_code></captcha_code>");
            return false;
         }
      }
      $checkemail = JRequest::getString('checkemail', '');
      
      $db = PFactory::getDbo();

      $user = JobHelper::getUserByEmail($checkemail);
      $subaccount = false; 
      if (!$user) {
         if(OC_User::userExists($checkemail, 'user_joomla')) {
            $subaccount = true; 
         }
         else {
            $this->setError("该邮箱地址不存在，请检查您输入的邮箱是否正确");
            return false;
         }
      }

      $token = hash('sha256', OC_Util::generate_random_bytes(30).OC_Config::getValue('passwordsalt', ''));

      if(!$subaccount) {
         // insert a token 
         // Hash the token again to prevent timing attacks
         $sql = "UPDATE #__comprofiler SET passwdreset_token = " . $db->quote(hash('sha256', $token)) . " WHERE user_id = " . $user->id; 
         $db->setQuery($sql);
         if(!$db->query()) {
            $this->setError("SQL DB error");
            return false; 
         }

      }
      else {
         // Hash the token again to prevent timing attacks
         OC_Preferences::setValue($checkemail, 'owncloud', 'lostpassword', hash('sha256', $token));
      }

      $reset_link = OC_Helper::makeURLAbsolute(OC_Helper::linkToRoute('company_passwdreset')) ."?token=$token&email=" . OC_Util::sanitizeHTML($checkemail);
      $reset_link = '<a href="' . $reset_link . '">' . $reset_link  . '</a>';
      require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
      $mailer = new JobmailModelEmail(); 
      $config = PFactory::getConfig();
      $receiver = (isDevMode() || isTestMode() || isTestUser($checkemail)) ? $config->get('employeremail', '') : $checkemail;
      $supportmail = $config->get('mailfrom','');
      $body = '<p class="p1"><b>'.($subaccount ? OC_User::getDisplayName($checkemail) : $user->name).'，您好！</b></p>
                  <p class="p3" style="margin-top:10px;">您申请了密码重置要求，请点击下面的重置链接来更新密码：</p>
                  <p class="p3">' . $reset_link . '</p>
                  <p class="p3 p4 p_last">如无法点击，请将链接拷贝至浏览器地址栏直接访问。</p>';

      $mailer->setTemplate('hrsimple');
      $mailer->setVariables(array(
                 'recipient'=>$receiver,
                 'fromName'=>'枇杷派云招聘',
                 'subject'=>'您的密码重置通知',
                 'supportmail'=>$supportmail,
                 'hrurl'=>'http://'.OC_Request::serverHost(),
                 'body'=>$body
         )
      );

      $mailer->send();
      return true; 
   }

   /* set password for cloud users (sub accounts) */
   public function setPassword() {
      if(!PSession::checkToken('post')) {
         $this->setError('登录已失效，请重新登录');
         return false; 
      }

      $uid = OC_User::getUser();
      $currentpassword = JRequest::getString("currentpassword", "", "post", JREQUEST_NOTRIM);
      $newpassword = JRequest::getString("newpassword", "", "post", JREQUEST_NOTRIM);
      $newpassword_verify = JRequest::getString("newpassword_verify", "", "post", JREQUEST_NOTRIM);

      if(empty($newpassword)) {
         $this->setError("密码不能为空");
         return false;
      }

      if(!preg_match("/^[^\s]{6,255}$/i", $newpassword)) {
         $this->setError('请输入有效的密码，至少6个字符，可包含数字、字母或其他字符，不允许使用空格');
         return false;
      }

      if($newpassword != $newpassword_verify) {
         $this->setError("密码和验证密码不一致，请重试.");
         return false;
      }

      if(!OC_User::checkPassword($uid, $currentpassword)) {
         $this->setError("当前密码错误");
         return false; 
      }
      
      if(!OC_User::setPassword($uid, $newpassword)) {
         $this->setError('修改密码失败');
         return false; 
      }
      
      return true; 
   }

}
